#include "VarTable.h"
#include <string>
using namespace std;

VarTable::VarTable(){
	varIndex = map<string, VarTableEntry>();
	revIndex = map<int, VarTableEntry>();
	indexCount = 0;
}

int VarTable::addVar(string varName, int stmtNum){
	int index;

	map<string, VarTableEntry>::iterator entryIt;
	if((entryIt = varIndex.find(varName)) != varIndex.end()){
		index = entryIt->second.getEntryNo();
		entryIt->second.addStmtNumber(stmtNum);
		revIndex.at(index).addStmtNumber(stmtNum);
	}
	else{
		index = indexCount;
		VarTableEntry entry(varName, indexCount++);
		entry.addStmtNumber(stmtNum);
		varIndex.insert(make_pair(varName,entry));
		revIndex.insert(make_pair(index,entry));
	}

	return index;
}

bool VarTable::addVarNodeID(int varIndex, int nodeID){
	map<int, VarTableEntry>::iterator entryIt = revIndex.find(varIndex);
	if(entryIt == revIndex.end()) return false;
	 return entryIt->second.addNodeID(nodeID);
}

int VarTable::getIndex(string varName){
	map<string, VarTableEntry >::iterator entryIt = varIndex.find(varName);
	if(entryIt == varIndex.end()) return -1;
	return entryIt->second.getEntryNo();
}

string VarTable::getVarName(int varIndex){
	map<int, VarTableEntry>::iterator entryIt = revIndex.find(varIndex);
	if(entryIt == revIndex.end()) return "";
	return entryIt->second.getName();
}

vector<int> VarTable::getStmts(int varIndex){
	map<int, VarTableEntry>::iterator entryIt = revIndex.find(varIndex);
	if(entryIt == revIndex.end()) return vector<int>();
	return entryIt->second.getStmtNumbers();
}

vector<int> VarTable::getNodeIDs(int varIndex){
	map<int, VarTableEntry>::iterator entryIt = revIndex.find(varIndex);
	if(entryIt == revIndex.end()) return vector<int>();
	return entryIt->second.getNodeIDs();
}

int VarTable::size(){
	return indexCount;
}